package com.wt.controller.controller.login;

import com.wt.controller.model.base.ErrorModel;
import com.wt.controller.model.base.SuccessModel;
import com.wt.dao.demo.model.LoginTimes;
import com.wt.service.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    private final static Logger LOGGER = Logger.getLogger(LoginController.class);

    @RequestMapping("login")
    @ResponseBody
    public Object index(String loginName,String passWord,HttpServletRequest request)
    {
        LOGGER.info("loginName="+loginName+",passWord"+passWord);

        Integer result ;
        try
        {
            result = loginService.login(loginName,passWord,request);
        }
        catch (Exception e)
        {
            LOGGER.error(e);
            return new ErrorModel("登录失败");
        }

        if(null == result)
        {
            return new ErrorModel("登录失败");
        }
        HttpSession session = request.getSession();
        session.setAttribute("userId", result);
        return new SuccessModel(result);
    }

    @RequestMapping("main")
    @ResponseBody
    public ModelAndView main(Integer userId,HttpServletRequest request)
    {
        HttpSession httpSession = request.getSession();
        ModelAndView view = new ModelAndView("/demo/main");
        view.addObject("userId", httpSession.getAttribute("userId"));
        return view;
    }

    @RequestMapping("getLoginTimes")
    @ResponseBody
    public Object getLoginTimes(String userId,HttpServletRequest request)
    {
        if(StringUtils.isBlank(userId))
        {
            LOGGER.error("用户id为空！");
            return new ErrorModel();
        }

        LoginTimes loginTimes = null;

        try
        {
            loginTimes = loginService.getLoginTimes(Integer.valueOf(userId),request);
        }
        catch (Exception e)
        {
            LOGGER.error(e);
            return new ErrorModel("登录失败");
        }

        return new SuccessModel(loginTimes);
    }


}
